﻿using Furion.DependencyInjection;
using Furion.FriendlyException;
using SqlSugar.Extensions;
using System.Diagnostics;
using System.Reflection;
using System.Text;

namespace Robotec.NET.Application;
/// <summary>
/// 数据迁移服务
/// </summary>
[ApiDescriptionSettings(ApplicationConst.GroupName, Order = 100)]
public partial class SysDataTransferService : IDynamicApiController, ITransient
{
    protected readonly SqlSugarRepository<SysDataTransfer> _rep;
    public SysDataTransferService(SqlSugarRepository<SysDataTransfer> rep)
    {
        _rep = rep;
    }
    #region 代码生成
    /// <summary>
    /// 分页查询数据迁移
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Page")]
    public virtual async Task<SqlSugarPagedList<SysDataTransferOutput>> Page(SysDataTransferInput input)
    {
      var context = _rep.AsQueryable().FilterDelete();
      if (context.UseCustomeSelectFlag())
      {
          return await context.CustomToSelect<SysDataTransfer,SysDataTransferOutput>(input);
      }
      else
      {
        var query= context.CustomWhere(input)
            .WhereIF(!string.IsNullOrWhiteSpace(input.SearchKey), u =>
                u.SourceConnectionString.Contains(input.SearchKey.Trim())
                || u.SourceConfigId.Contains(input.SearchKey.Trim())
                || u.SourceDbName.Contains(input.SearchKey.Trim())
                || u.TargetConfigId.Contains(input.SearchKey.Trim())
                || u.TargetDbName.Contains(input.SearchKey.Trim())
                || u.TargetConnectionString.Contains(input.SearchKey.Trim())
            )
            .WhereIF(!string.IsNullOrWhiteSpace(input.SourceConnectionString), u => u.SourceConnectionString.Contains(input.SourceConnectionString.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.SourceConfigId), u => u.SourceConfigId.Contains(input.SourceConfigId.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.SourceDbName), u => u.SourceDbName.Contains(input.SourceDbName.Trim()))
            .WhereIF(input.SourceDbType.HasValue, u => u.SourceDbType == input.SourceDbType)
        .WhereIF(input.ClearTargetTableFlag.HasValue, u => u.ClearTargetTableFlag == input.ClearTargetTableFlag)
            .WhereIF(!string.IsNullOrWhiteSpace(input.TargetConfigId), u => u.TargetConfigId.Contains(input.TargetConfigId.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.TargetDbName), u => u.TargetDbName.Contains(input.TargetDbName.Trim()))
            .WhereIF(input.TargetDbType.HasValue, u => u.TargetDbType == input.TargetDbType)
            .WhereIF(!string.IsNullOrWhiteSpace(input.TargetConnectionString), u => u.TargetConnectionString.Contains(input.TargetConnectionString.Trim()))
            .OrderByDescending(r=>r.UpdateTime)
            .Select<SysDataTransferOutput>()
;
          
       
        return await query.CustomToPagedListAsync(input);
      }
    }

    /// <summary>
    /// 增加数据迁移
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Add")]
    public async Task<JRResult<string>> Add(AddSysDataTransferInput input)
    {
        var entity = input.Adapt<SysDataTransfer>();
         var doSomeResult = await  entity.DoSomeThing(_rep.Context);
        if (!doSomeResult.Item1)
            return CustomeResult.Fail<string>(doSomeResult.Item2);
        bool isNeedReplicatings=false;
        string repString=null;
        Expression<Func<SysDataTransfer, bool>> whereExpression = r => true;
        whereExpression = whereExpression.And(r => r.SourceConfigId == entity.SourceConfigId);
        isNeedReplicatings=true;
        repString+="源数据库配置编号";
         if (isNeedReplicatings)
        {
            isNeedReplicatings = await _rep.IsAnyAsync(whereExpression);
            if (!isNeedReplicatings){
              await _rep.InsertAsync(entity);
            }
            else
            {
                //系统中存在已删除数据，还原数据
                whereExpression = whereExpression.And(r => r.IsDelete == true);
                var exsitModel = await _rep.GetFirstAsync(whereExpression);
                if (exsitModel != null)
                {
                    entity.Id = exsitModel.Id; //还原已删除的数据
                    entity.IsDelete = false;
                       await _rep.UpdateAsync(entity);
                    isNeedReplicatings = false;
                }
            }
        }
        else{
              await _rep.InsertAsync(entity);
        }
        return new JRResult<string>
        {
            Code = !isNeedReplicatings ? StatusCodes.Status200OK : StatusCodes.Status400BadRequest,
            Message = !isNeedReplicatings ? "新增成功！" : $"系统中存在重复的【{repString}】，不能重复添加！",
            Result = null,
            Type = !isNeedReplicatings ? "success" : "error",
            Extras = UnifyContext.Take(),
            Time = DateTime.Now
        };
    }

    /// <summary>
    /// 删除数据迁移
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Delete")]
    public virtual async Task Delete(DeleteSysDataTransferInput input)
    {
        var entity = await _rep.GetFirstAsync(u => u.Id == input.Id) ?? throw Oops.Oh(ErrorCodeEnum.D1002);
        await _rep.FakeDeleteAsync(entity);   //假删除
    }

    /// <summary>
    /// 更新数据迁移
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Update")]
    public async Task<JRResult<string>> Update(UpdateSysDataTransferInput input)
    {
        var entity = input.Adapt<SysDataTransfer>();
        var doSomeResult = await  entity.DoSomeThing(_rep.Context);
        if (!doSomeResult.Item1)
            return CustomeResult.Fail<string>(doSomeResult.Item2);
        bool isNeedReplicatings = false;
        string repString=null;
        Expression<Func<SysDataTransfer, bool>> whereExpression = r => r.Id != entity.Id;
        whereExpression = whereExpression.And(r => r.SourceConfigId == entity.SourceConfigId);
        isNeedReplicatings=true;
        repString+="源数据库配置编号";
         if (isNeedReplicatings)
        {
            isNeedReplicatings = await _rep.IsAnyAsync(whereExpression);
            if (!isNeedReplicatings){
                await _rep.AsUpdateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
                await entity.DoSomeThingSaveChildren(_rep.Context);
            }
        }
        else
           {
                await _rep.AsUpdateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
                await entity.DoSomeThingSaveChildren(_rep.Context);
           }

        return new JRResult<string>
        {
            Code = !isNeedReplicatings ? StatusCodes.Status200OK : StatusCodes.Status400BadRequest,
            Message = !isNeedReplicatings ? "更新成功！" : $"系统中存在重复的【{repString}】，不能修改！",
            Result = null,
            Type = !isNeedReplicatings ? "success" : "error",
            Extras = UnifyContext.Take(),
            Time = DateTime.Now
        };
    }

    /// <summary>
    /// 保存数据迁移
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "Save")]
    public async Task<JRResult<string>> Save(UpdateSysDataTransferInput input)
    {
        var entity = input.Adapt<SysDataTransfer>();
        await  entity.SaveDoSomeThing(_rep.Context);
        bool isNeedReplicatings = false;
        string repString=null;
        Expression<Func<SysDataTransfer, bool>> whereExpression = r => r.Id != entity.Id;
        whereExpression = whereExpression.And(r => r.SourceConfigId == entity.SourceConfigId);
        isNeedReplicatings=true;
        repString+="源数据库配置编号";
         if (isNeedReplicatings)
        {
            isNeedReplicatings = await _rep.IsAnyAsync(whereExpression);
            if (!isNeedReplicatings)
               {
                await _rep.AsUpdateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
                await entity.DoSomeThingSaveChildren(_rep.Context);
               }
        }
        else
            {
                await _rep.AsUpdateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
                await entity.DoSomeThingSaveChildren(_rep.Context);
            }

        return new JRResult<string>
        {
            Code = !isNeedReplicatings ? StatusCodes.Status200OK : StatusCodes.Status400BadRequest,
            Message = !isNeedReplicatings ? "更新成功！" : $"系统中存在重复的【{repString}】，不能修改！",
            Result = null,
            Type = !isNeedReplicatings ? "success" : "error",
            Extras = UnifyContext.Take(),
            Time = DateTime.Now
        };
    }

        /// <summary>
    /// 保存数据迁移包含关联表
    /// </summary>
    /// <param name="entity"></param>
    /// <returns></returns>
    [HttpPost]
    [ApiDescriptionSettings(Name = "SaveWithChildren")]
    public async Task<JRResult<string>> SaveWithChildren(SysDataTransfer entity)
    {
        await  entity.SaveDoSomeThing(_rep.Context);
        bool isNeedReplicatings = false;
        string repString=null;
        Expression<Func<SysDataTransfer, bool>> whereExpression = r => r.Id != entity.Id;
        whereExpression = whereExpression.And(r => r.SourceConfigId == entity.SourceConfigId);
        isNeedReplicatings=true;
        repString+="源数据库配置编号";
         if (isNeedReplicatings)
        {
            isNeedReplicatings = await _rep.IsAnyAsync(whereExpression);
            if (!isNeedReplicatings)
               {
                await _rep.AsUpdateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
                await entity.DoSomeThingSaveChildren(_rep.Context);
               }
        }
        else
            {
                await _rep.AsUpdateable(entity).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync();
                await entity.DoSomeThingSaveChildren(_rep.Context);
            }

        return new JRResult<string>
        {
            Code = !isNeedReplicatings ? StatusCodes.Status200OK : StatusCodes.Status400BadRequest,
            Message = !isNeedReplicatings ? "更新成功！" : $"系统中存在重复的【{repString}】，不能修改！",
            Result = null,
            Type = !isNeedReplicatings ? "success" : "error",
            Extras = UnifyContext.Take(),
            Time = DateTime.Now
        };
    }

    /// <summary>
    /// 获取数据迁移
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpGet]
    [ApiDescriptionSettings(Name = "Detail")]
    public async Task<SysDataTransfer> Get([FromQuery] QueryByIdSysDataTransferInput input)
    {
        return await _rep.GetFirstAsync(u => u.Id == input.Id);
    }

     /// <summary>
    /// 获取数据迁移详情
    /// </summary>
    [HttpGet]
    public async Task<dynamic> Info(string tableName, long id)
    {
        var logConfigId = SqlSugarConst.GetDataBaseConfigId(tableName);
        var _db = _rep.AsTenant().GetConnectionScope(logConfigId);
        var tableInfo = SqlSugarConst.GetDdataBaseFullName(tableName);
        var dt = await _db.SqlQueryable<dynamic>($"select * from {tableInfo} where Id={id}").ToListAsync();
        dynamic clay = Clay.Object(dt.FirstOrDefault());
        return TypeHelper.SetDynamicZh(tableName, clay);
    }

    /// <summary>
    /// 获取数据迁移列表
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [HttpGet]
    [ApiDescriptionSettings(Name = "List")]
    public async Task<List<SysDataTransferOutput>> List([FromQuery] SysDataTransferInput input)
    {
        return await _rep.AsQueryable().Select<SysDataTransferOutput>().ToListAsync();
    }





    /// <summary>
    /// 导出数据迁移
    /// </summary>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "Export"), NonUnify]
    public async Task<IActionResult> Export(SysDataTransferInput input)
    {
          var context = _rep.AsQueryable().FilterDelete();
      if (context.UseCustomeSelectFlag())
      {
          var list= await context.CustomToSelectExport<SysDataTransfer,ExportImportSysDataTransferDto>(input);
          IExcelExporter excelExporter = new ExcelExporter();
          var res = await excelExporter.ExportAsByteArray(list);
          return new FileStreamResult(new MemoryStream(res), "application/octet-stream") { FileDownloadName = DateTime.Now.ToString("yyyyMMddHHmm") + "生产模式切换记录表.xlsx" };
      }
      else
      {
      
        var query= _rep.AsQueryable().FilterDelete().CustomWhere(input)
            .WhereIF(!string.IsNullOrWhiteSpace(input.SearchKey), u =>
                u.SourceConnectionString.Contains(input.SearchKey.Trim())
                || u.SourceConfigId.Contains(input.SearchKey.Trim())
                || u.SourceDbName.Contains(input.SearchKey.Trim())
                || u.TargetConfigId.Contains(input.SearchKey.Trim())
                || u.TargetDbName.Contains(input.SearchKey.Trim())
                || u.TargetConnectionString.Contains(input.SearchKey.Trim())
            )
            .WhereIF(!string.IsNullOrWhiteSpace(input.SourceConnectionString), u => u.SourceConnectionString.Contains(input.SourceConnectionString.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.SourceConfigId), u => u.SourceConfigId.Contains(input.SourceConfigId.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.SourceDbName), u => u.SourceDbName.Contains(input.SourceDbName.Trim()))
            .WhereIF(input.SourceDbType.HasValue, u => u.SourceDbType == input.SourceDbType)
        .WhereIF(input.ClearTargetTableFlag.HasValue, u => u.ClearTargetTableFlag == input.ClearTargetTableFlag)
            .WhereIF(!string.IsNullOrWhiteSpace(input.TargetConfigId), u => u.TargetConfigId.Contains(input.TargetConfigId.Trim()))
            .WhereIF(!string.IsNullOrWhiteSpace(input.TargetDbName), u => u.TargetDbName.Contains(input.TargetDbName.Trim()))
            .WhereIF(input.TargetDbType.HasValue, u => u.TargetDbType == input.TargetDbType)
            .WhereIF(!string.IsNullOrWhiteSpace(input.TargetConnectionString), u => u.TargetConnectionString.Contains(input.TargetConnectionString.Trim()))
            .Select<ExportImportSysDataTransferDto>()
;
        query = query.CustomeOrder(input);
        var list=await query.ToListAsync();
        IExcelExporter excelExporter = new ExcelExporter();
        var res = await excelExporter.ExportAsByteArray(list);
        return new FileStreamResult(new MemoryStream(res), "application/octet-stream") { FileDownloadName = DateTime.Now.ToString("yyyyMMddHHmm") + "数据迁移.xlsx" };
     }
  }

     /// <summary>
    /// 导入
    /// </summary>
    /// <param name="file"></param>
    /// <returns></returns>
    [HttpPost]
    public async Task<JRResult<string>> Import(IFormFile file)
    {
        IImporter Importer = new ExcelImporter();
        var importData = await Importer.Import<ExportImportSysDataTransferDto>(file.OpenReadStream());
        if (importData.HasError == true) { return CustomeResult.Fail<string>("导入错误");  }
        if (importData.Exception != null) { return CustomeResult.Fail<string>(importData.Exception.ToString());  }
        if (importData.RowErrors.Count > 0) { return CustomeResult.Fail<string>(JSON.Serialize(importData.RowErrors));  }
        if (importData.Data == null) {return CustomeResult.Fail<string>("导入的数据量不能为空！");  }
        if (importData.Data.Count <= 0) { return CustomeResult.Fail<string>("导入的数据量为0个！"); }
       
            var models = importData.Data.Adapt<List<SysDataTransfer>>();
            bool isNeedReplicatings = false;
            string repString=null;
            Expression<Func<SysDataTransfer, bool>> whereExpression = r => true;
             whereExpression = whereExpression.And(r => models.Select(c => c.SourceConfigId).Contains(r.SourceConfigId));
             isNeedReplicatings=true;
             repString+="【源数据库配置编号重复】";
             if(models.GroupBy(r=>r.SourceConfigId).Any(c=>c.Count()>1)){return CustomeResult.Fail<string>(repString);}
              if (isNeedReplicatings)
             {
                 isNeedReplicatings = await _rep.IsAnyAsync(whereExpression);
                
                 if (!isNeedReplicatings){
                      await _rep.AsInsertable(models).ExecuteCommandAsync();
                 }
                 else
                      return CustomeResult.Fail<string>(repString);
             }else{
                      await _rep.AsInsertable(models).ExecuteCommandAsync();
             }
        
      return CustomeResult.Success<string>("导入成功!");
    }


    /// <summary>
    /// 模板下载
    /// </summary>
    /// <returns></returns>
    [AllowAnonymous]
    [HttpGet]
    public async Task<IActionResult> TemplateDown()
    {
        IImporter Importer = new ExcelImporter();
        var template = await Importer.GenerateTemplateBytes<ExportImportSysDataTransferDto>();
        return new FileStreamResult(new MemoryStream(template), "application/octet-stream") { FileDownloadName = DateTime.Now.ToString("yyyyMMddHHmm") + "数据迁移导入模板.xlsx" };
    }
    #endregion

    /// <summary>
    /// 整个库迁移
    /// </summary>
    /// <returns></returns>
    [HttpGet]
    public virtual async Task<JRResult<string>> TransferAllDataBase([FromQuery] string? sourceConfigId = null)
    {
        var configSourceConfigIds = await CommonUtil.GetConfigRemarkSplits(CommonConst.BakDataBase, CommonConst.SplitString);
        if (sourceConfigId.IsNullOrEmpty() && configSourceConfigIds.Length <= 0)
            return CustomeResult.Fail("未配置数据库迁移的数据！");

        var list = await _rep.Context.MyQueryable<SysDataTransfer>()
            .WhereIF(!sourceConfigId.IsNullOrEmpty(), r => r.SourceConfigId == sourceConfigId)
            .WhereIF(sourceConfigId.IsNullOrEmpty() && configSourceConfigIds.Length > 0, r => configSourceConfigIds.Contains(r.SourceConfigId))
            .ToListAsync();
        if (list.Count > 2)
        {
            return CustomeResult.Fail("只能用两行数据来迁移整个库！");
        }
        return await StartTransfer(list);
    }
    /// <summary>
    /// 开始迁移
    /// </summary>
    /// <param name="input"></param>
    /// <returns></returns>
    [ApiDescriptionSettings(Name = "StartTransfer")]
    [HttpPost]
    public virtual async Task<JRResult<string>> StartTransfer(List<SysDataTransfer> inputs)
    {
        return await Transfer(inputs);
    }
    private async Task<JRResult<string>> Transfer(List<SysDataTransfer> inputs)
    {
        int pageSize = await CommonUtil.GetConfigRemarkToInt(CommonConst.TransferPageSize);
        if (pageSize <= 0)
            pageSize = 5000;

        var currentSystemDbOptions = App.GetOptions<DbConnectionOptions>();
        inputs = await _rep.Context.MyQueryable<SysDataTransfer>().Where(r => inputs.Select(c => c.Id).Contains(r.Id)).ToListAsync();
        StringBuilder errorSp = new StringBuilder();
        StringBuilder messageSp = new StringBuilder();
        Func<string, Func<Type, bool>> myFunc = (typeName) =>
        {
            Func<Type, bool> func = u => true;
            switch (typeName)
            {
                case nameof(BusinessVSAttribute):
                    func = u => u.GetCustomAttributes<BusinessVSAttribute>().Any();
                    break;
                case nameof(BusinessWmsAttribute):
                    func = u => u.GetCustomAttributes<BusinessWmsAttribute>().Any();
                    break;
                case nameof(SysTableAttribute):
                    func = u => u.GetCustomAttributes<SysTableAttribute>().Any();
                    break;
                case nameof(LogTableAttribute):
                    func = u => u.GetCustomAttributes<LogTableAttribute>().Any();
                    break;
            }
            return func;
        };

        foreach (var input in inputs)
        {
            Stopwatch sw = new Stopwatch();
            sw.Start();
            SqlSugarClient sourceDB = new SqlSugarClient(new ConnectionConfig()
            {
                ConfigId = input.SourceConfigId,
                ConnectionString = input.SourceConnectionString,
                DbType = (SqlSugar.DbType)input.SourceDbType,
                IsAutoCloseConnection = true
            });

            var sourceSeting = currentSystemDbOptions.ConnectionConfigs.FirstOrDefault(cc => cc.ConfigId == input.SourceConfigId || cc.ConnectionString.Trim().ToLower() == input.SourceConnectionString.Trim().ToLower());
            var sourceConnectionConfig = new DbConnectionConfig()
            {
                ConfigId = input.SourceConfigId,
                ConnectionString = input.SourceConnectionString,
                DbType = (SqlSugar.DbType)input.SourceDbType,
                IsAutoCloseConnection = true,
                DbSettings = sourceSeting?.DbSettings,
                TableSettings = sourceSeting?.TableSettings
            };

            //目标数据库配置
            var targetC = currentSystemDbOptions.ConnectionConfigs.FirstOrDefault(cc => cc.ConfigId == input.TargetConfigId || cc.ConnectionString.Trim().ToLower() == input.TargetConnectionString.Trim().ToLower());
            var targetConnectionConfig = new DbConnectionConfig()
            {
                ConfigId = input.TargetConfigId,
                ConnectionString = input.TargetConnectionString,
                DbType = (SqlSugar.DbType)input.TargetDbType,
                IsAutoCloseConnection = true,
                DbSettings = targetC?.DbSettings,
                TableSettings = targetC?.TableSettings
            };


            targetConnectionConfig.DbSettings = new DbSettings();
            targetConnectionConfig.DbSettings.EnableUnderLine = false;
            if (targetConnectionConfig.TableSettings == null)
                targetConnectionConfig.TableSettings = sourceConnectionConfig.TableSettings;

            SqlSugarSetup.SetDbConfig(targetConnectionConfig);
            SqlSugarScope targetDB = new SqlSugarScope(targetConnectionConfig.Adapt<ConnectionConfig>(), db =>
            {
                var dbProvider = db.GetConnectionScope(input.TargetConfigId);
                SqlSugarSetup.SetDbAop(dbProvider, true);
            });
            //系统中所有Sqlsugar模型
            var entityTypes = App.EffectiveTypes
               .Where(u => !u.IsInterface && !u.IsAbstract && u.IsClass && u.IsDefined(typeof(SugarTable), false))
                   .ToList();

            //MpwStationInput
            //需要排除的表
            if (input.SourceExcludeTables != null && !input.SourceExcludeTables.Any(r => r.IsNullOrEmpty()) && input.SourceExcludeTables.Count > 0)
            {
                entityTypes = entityTypes.Where(r => !input.SourceExcludeTables.Select(c => c.ToUpper()).Contains(r.Name.ToUpper())).ToList();
                var TEMP = entityTypes.Where(r => r.GetCustomAttribute<SugarTable>() != null &&
                 !r.GetCustomAttribute<SugarTable>().TableName.IsNullOrEmpty() &&
                 input.SourceExcludeTables.Select(c => c.ToUpper()).Contains(r.GetCustomAttribute<SugarTable>().TableName.ToUpper())).ToList();
                if (TEMP.Count > 0)
                {
                    entityTypes = entityTypes.Where(r => !TEMP.Select(c => c.Name.ToUpper()).Contains(r.Name.ToUpper())).ToList();
                }
            }
            //只更新的表
            if (input.SourceOnlyTransferTables != null && !input.SourceOnlyTransferTables.Any(r => r.IsNullOrEmpty()) && input.SourceOnlyTransferTables.Count > 0)
                entityTypes = entityTypes.Where(r => input.SourceOnlyTransferTables.Select(c => c.ToUpper()).Contains(r.Name.ToUpper())).ToList();


            if (input.TargetDbType != MyDbType.Oracle)
                targetDB.DbMaintenance.CreateDatabase();

            //根据特性找到需要迁移的数据表
            foreach (var attrOne in input.SourceTableAttribute)
            {
                var needTransferTables = entityTypes.Where(myFunc(attrOne)).ToList();
                #region 更新表结构
                foreach (var entityType in needTransferTables.Where(r => r.GetCustomAttribute<SqlLiteNotMapperTableUpdateAttribute>() == null))
                {
                    try
                    {
                        if (entityType.GetCustomAttribute<SplitTableAttribute>() == null)
                            targetDB.CodeFirst.InitTables(entityType);
                    }
                    catch (Exception ex)
                    {
                        errorSp.AppendLine(ex.ToString());
                    }
                }
                #endregion

                #region 数据迁移

                foreach (var entityType in needTransferTables)
                {
                    if (entityType.GetCustomAttribute<SplitTableAttribute>() == null)
                    {
                        //模型名称可能与表名不一致，所以读取SugarTable真正的表名
                        string entityTypeName = entityType.Name;
                        var table = entityType.GetCustomAttribute<SugarTable>();
                        if (table != null && !table.TableName.IsNullOrEmpty())
                            entityTypeName = table.TableName;

                        if (targetConnectionConfig.TableSettings != null)
                            entityTypeName = targetConnectionConfig.TableSettings.TablePrefix + entityTypeName + targetConnectionConfig.TableSettings.TableSuffix;


                        try
                        {
                            #region OLD 2024-07-25 旧的同步方法
                            //var dataList = await sourceDB.QueryableByObject(entityType).ToListAsync();
                            //int dataCount = 0;
                            //ICollection col = dataList as ICollection;
                            //if (col != null)
                            //{
                            //    dataCount = col.Count;
                            //}
                            //if (input.ClearTargetTableFlag && dataCount > 0)
                            //    await targetDB.Deleteable<object>().AS(entityTypeName).ExecuteCommandAsync();
                            //if (dataList != null && dataCount > 0)
                            //    await targetDB.InsertableByObject(dataList).ExecuteCommandAsync();
                            #endregion

                            #region 新的同步方法
                            int dataCount = 0;
                            var numbers = sourceDB.Ado.SqlQuery<string>($"select count(1) as cou from {entityTypeName.ToLower()}");
                            dataCount = numbers.FirstOrDefault().ObjToInt();

                            if (input.ClearTargetTableFlag && dataCount > 0)
                                await targetDB.Deleteable<object>().AS(entityTypeName).ExecuteCommandAsync();

                            var TotalPages = (int)Math.Ceiling(dataCount / (double)pageSize);
                            for (int currentPage = 1; currentPage <= TotalPages; currentPage++)
                            {
                                var dataList = await sourceDB.QueryableByObject(entityType).AS(entityTypeName).ToPageListAsync(currentPage, pageSize);
                                if (dataList != null)
                                    await targetDB.InsertableByObject(dataList).ExecuteCommandAsync();
                            }
                            #endregion

                            messageSp.AppendLine($"迁移数据表：{entityTypeName},插入数据条数：{dataCount}!");
                        }
                        catch (Exception ex)
                        {
                            errorSp.AppendLine(ex.ToString());
                        }
                    }
                    else
                    {
                        messageSp.AppendLine($"排除数据表：{entityType.Name}!");
                    }
                }
                #endregion

            }
            sw.Stop();
            input.Description = $"【迁移[{input.SourceConfigId}]到目标[{input.TargetConfigId}]耗时：{sw.ElapsedMilliseconds}】\r\n";
            if (input.SourceExcludeTables != null && input.SourceExcludeTables.Count > 0)
                messageSp.AppendLine($"【排除数据表：{string.Join(",", input.SourceExcludeTables)}】");
            input.Description += messageSp.ToString() + errorSp.ToString();
            input.UpdateTime = DateTime.Now;
        }
        await _rep.Context.MyUpdateable<SysDataTransfer>(inputs).UpdateColumns(r => new { r.Description, r.UpdateTime }).ExecuteCommandAsync();
        return CustomeResult.Success();
    }


}

